//
//  WBStatusListViewModel.swift
//  Weibo
//
//  Created by yinbo on 2018/3/6.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
import SDWebImage
//上拉刷新最大尝试次数
private let maxPullupTryTimes = 3
//父类的选择：1.如果类需要使用'kvc'或者字典转模型框架设置对象值，类就需要继承自NSObject;2.如果类只是包装一些代码逻辑（写了一些函数），可以不用任何父类，好处：更加轻量级
class WBStatusListViewModel: NSObject {
    lazy var statusList = [WBStatusViewModel]()
    private var pullupErrorTimes = 0
    func loadStatus(pullup:Bool=false,comletion:@escaping (_ isSuccess:Bool , _ shouldRefresh:Bool)->()){
        if pullup && pullupErrorTimes > maxPullupTryTimes{
            comletion(true,false)
            return
        }
        
        //since_id 取出数组中第一条微博的ID
        let
        
        since_id = statusList.first?.status.id ?? 0
        
        let max_id = !pullup ? 0 :(statusList.last?.status.id ?? 0)
        WBNetworkManager.shared.statusList(since_id: since_id,max_id: max_id) { (list, isSuccess) in
            if !isSuccess {
                comletion(false,false)
                return
            }
            var array = [WBStatusViewModel]()
            for dict in list ?? []{
                guard let model = WBStatus.yy_model(with: dict) else{
                    continue
                }
                
                 array.append(WBStatusViewModel(model: model))
            }
//            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else{
//                    comletion(isSuccess,false)
//                    return
//            }
            
            if pullup {
                self.statusList += array

            }else{
                self.statusList = array + self.statusList

            }
            if pullup && array.count == 0{
                self.pullupErrorTimes += 1
                comletion(isSuccess,false)
                
                
            }else{
                self.cacheSingleImage(list: array, comletion: comletion)
//                comletion(isSuccess,true)
            }
            

        }
    }
    //缓存本次下载微博数据数组中的单张图像
    func cacheSingleImage(list:[WBStatusViewModel],comletion:@escaping (_ isSuccess:Bool , _ shouldRefresh:Bool)->()){
        let group = DispatchGroup()
        var length = 0
        for vm in list {
            if vm.picURLs?.count != 1 {
                continue
            }
            guard let pic = vm.picURLs![0].thumbnail_pic,let url = URL(string: pic) else{
                continue
            }
            //下载图片
            //dowmloadIMage 是SDWebImage的核心方法
            //图片下载完成之后，会自动保存到沙盒中，文件路径是URL的md5
            //如果沙盒中依旧存在缓存的图像，后续使用SD通过URL加载图片，都会加载本地沙何的图像
            //不会发起网络请求，同时，回调方法，同样会调用
            //方法还是同样的方法，调用还是同样的调用，不过内部不会再次发起网络请求
            //注意点：如果要缓存的图像累计很大，要找后台要接口
            
            
            //入组
            group.enter()
            let dowmloader = SDWebImageManager.shared().imageDownloader
            dowmloader?.downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _) in
                //将图像转换成二进制数据
                if let image = image,let data = UIImagePNGRepresentation(image){
                    length += data.count
                    vm.updateSingleImageSize(image: image)
                }
                print("缓存的图像\(image),长度：\(length)")
                
                group.leave()
            })
            
        }
        group.notify(queue: DispatchQueue.main) { 
            print("图片缓存成功\(length/2014)K")
            comletion(true,true)
        }
    }

}
